/*
 * @lc app=leetcode.cn id=530 lang=cpp
 *
 * [530] 二叉搜索树的最小绝对差
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    int lastValue = 0;      // 记录上一个访问节点的值
    int minDifference = 0;  // 记录最小的差值

    int getMinimumDifference(TreeNode* root) {
        // 初始化相关变量
        lastValue = -1;
        minDifference = INT_MAX;
        dfs(root);
        return minDifference;
    }

    // 中序遍历，升序访问
    void dfs(TreeNode* root) {
        if (root == nullptr) return;
        dfs(root->left);
        
        // 更新相关变量
        if (lastValue != -1 && root->val - lastValue < minDifference) {
            minDifference = root->val - lastValue;
        }
        lastValue = root->val;
        
        dfs(root->right);
    }
};
// @lc code=end
